package control;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;

import dao.DAOFactory;
import dao.Entidad;

import bean.Cliente;

/**
 * Servlet implementation class Servlet
 */
@WebServlet("/ServletCliente")
public class ServletCliente extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletCliente() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		if(request.getParameter("action")!=null){
			String action=(String)request.getParameter("action");
			List<Cliente> listCliente= new ArrayList<Cliente>();
			GsonBuilder builder = new GsonBuilder();
			builder.setDateFormat("yyyy-MM-dd");
			Gson gson = builder.create();
			response.setContentType("application/json");
			
			DAOFactory factory=DAOFactory.getFactoryConcrete(DAOFactory.MYSQL);
			Entidad<Cliente> clientedao= factory.getClienteDAO(); //DFCC
			
			if(action.equals("list")){
				try{
					
					listCliente = clientedao.listAll();					
					
					JsonElement element = gson.toJsonTree(listCliente,new TypeToken<List<Cliente>>(){}.getType());
					JsonArray jsonArray = element.getAsJsonArray();
					String listData=jsonArray.toString();
					
					listData="{\"Result\":\"OK\",\"Records\":"+listData+"}";					
					
					response.setHeader("Cache-control", "no-cache, no-store");
			        response.setHeader("Pragma", "no-cache");
			        response.setHeader("Expires", "-1");
					response.getWriter().print(listData);
					System.out.println(listData);
					
				}catch(Exception ex){
					String error="{\"Result\":\"ERROR\",\"Message\":"+ex.getStackTrace()+"}";
					response.getWriter().print(error);
					System.out.println(error);
				}
				
			}else if(action.equals("create") || action.equals("update")){
			    Cliente cliente=new Cliente();
			    
			    try{
			    	
			    if(request.getParameter("id_pers")!=null){       
				       int id_cliente=Integer.parseInt(request.getParameter("id_pers"));
				       cliente.setId_pers(id_cliente);
			    }
			    if(request.getParameter("nomb_pers")!=null){
				       String nombre=(String)request.getParameter("nomb_pers");
				       cliente.setNomb_pers(nombre);
			    }
			    if(request.getParameter("apel_pate")!=null){
				       String apellido_paterno=(String)request.getParameter("apel_pate");
				       cliente.setApel_pate(apellido_paterno);
			    }
			    if(request.getParameter("apel_mate")!=null){
				       String apellido_materno=(String)request.getParameter("apel_mate");
				       cliente.setApel_mate(apellido_materno);
			    }
			    if(request.getParameter("dni")!=null){
			    	   int dni=Integer.parseInt((String)(request.getParameter("dni")));
			    	   cliente.setDni(dni);
				}
			    if(request.getParameter("fech_naci")!=null){
			    	System.out.println("ENTRO A LA FECHA" + request.getParameter("fech_naci"));
					SimpleDateFormat format=
							new SimpleDateFormat("yyyy-MM-dd");
					Date fechaNacimiento=new Date();
					try {
						System.out.println("ENTRO AL TRY");
						fechaNacimiento=
						format.parse(request.getParameter("fech_naci"));
						cliente.setFech_naci(fechaNacimiento);
						System.out.println("PASOO");
					} catch (ParseException e) {
						
					}	
			    }
			    if(request.getParameter("naci")!=null){
			    	   String nacionalidad=((String)request.getParameter("naci"));
			    	   cliente.setNaci(nacionalidad);
				}
			    if(request.getParameter("dire")!=null){
				       String direccion=((String)request.getParameter("dire"));
				       cliente.setDire(direccion);
			    }
			    if(request.getParameter("celu")!=null){
				       int celular=Integer.parseInt((String)request.getParameter("celu"));
				       cliente.setCelu(celular);
				}
			  
			    if(request.getParameter("tele")!=null){
			    	 int telefono=Integer.parseInt((String)(request.getParameter("tele")));
			    	   cliente.setTele(telefono);
				}
			    if(request.getParameter("id_pais")!=null){
		    		int id_pais=Integer.parseInt((String)request.getParameter("id_pais"));
			       cliente.setId_pais(id_pais);
			    }
			    if(request.getParameter("id_depa")!=null){
		    		int id_departamento=Integer.parseInt((String)request.getParameter("id_depa"));
			       cliente.setId_depa(id_departamento);
			    }
			    if(request.getParameter("id_prov")!=null){
		    		int id_provincia=Integer.parseInt((String)request.getParameter("id_prov"));
			       cliente.setId_prov(id_provincia);
			    }
			    if(request.getParameter("id_dist")!=null){
		    		int id_distrito=Integer.parseInt((String)request.getParameter("id_dist"));
			       cliente.setId_dist(id_distrito);
			    }
			  
			    if(request.getParameter("ruc")!=null){
			    	 String ruc=(String)(request.getParameter("ruc"));
			    	   cliente.setRuc(ruc);
				}		    
			    }catch(Exception e){
			    	System.out.print("Error al capturar datos " + e.getMessage());
			    }
			    
			    try{           
			     if(action.equals("create")){//Create new record
			      clientedao.insert(cliente);     
			      listCliente.add(cliente); 
			      //Convert Java Object to Json    
			      String json=gson.toJson(cliente);     
			      //Return Json in the format required by jTable plugin
			      String listData="{\"Result\":\"OK\",\"Record\":"+json+"}";           
			      response.getWriter().print(listData);
			     }else if(action.equals("update")){//Update existing record
			    	 clientedao.update(cliente);
			      String listData="{\"Result\":\"OK\"}";         
			      response.getWriter().print(listData);
			     }
			    }catch(Exception ex){
			      String error="{\"Result\":\"ERROR\",\"Message\":"+ex.getStackTrace().toString()+"}";
			      response.getWriter().print(error);
			    }
			   }else if(action.equals("delete")){//Delete record
			    try{
			     if(request.getParameter("id_pers")!=null){
			     Cliente  cliente  =new Cliente();
			     	try{
			     		if(request.getParameter("id_pers")!=null){       
			     		int id_cliente=Integer.parseInt(request.getParameter("id_pers"));
			     		cliente.setId_pers(id_cliente);
						}
					}catch(Exception e){
					    System.out.print("Error al capturar datos " + e.getMessage());
					}
			     	clientedao.delete(cliente);
			      String listData="{\"Result\":\"OK\"}";        
			      response.getWriter().print(listData);
			     }
			    }catch(Exception ex){
			    String error="{\"Result\":\"ERROR\",\"Message\":"+ex.getStackTrace().toString()+"}";
			    response.getWriter().print(error);
			   }    
			  }
			
		}
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		doGet(request, response);
	}

}
